<template>
  <div>
    <div style="margin: 10px 0">
      <el-input style="width: 200px" placeholder="请输入标题" suffix-icon="el-icon-search" v-model="title"></el-input>

      <el-button class="ml-5" type="primary" @click="load">搜索</el-button>
      <el-button type="warning" @click="reset">重置</el-button>
    </div>
    <div style="margin: 10px 0">
      <el-button type="primary" @click="handleAdd">新增 <i class="el-icon-circle-plus-outline"></i></el-button>
      <el-popconfirm
          class="ml-5"
          confirm-button-text='确定'
          cancel-button-text='我再想想'
          icon="el-icon-info"
          icon-color="red"
          title="您确定批量删除这些数据吗？"
          @confirm="delBatch"
      >
        <el-button type="danger" slot="reference">批量删除 <i class="el-icon-remove-outline"></i></el-button>
      </el-popconfirm>
      <el-button type="primary" class="ml-5">导入 <i class="el-icon-bottom"></i></el-button>
      <el-button type="primary">导出 <i class="el-icon-top"></i></el-button>
    </div>
    <el-dialog :visible.sync="dialogVisible">
      <img :src="imageUrl" style="max-width: 100%; max-height: 100%;">
    </el-dialog>
    <el-table
        :data="tableData"
        border
        stripe
        :highlight-current-row="true"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>

      <el-table-column prop="title" label="文章标题">
      </el-table-column>

      <el-table-column prop="pictureUrl" label="文章封面">
        <template slot-scope="scope">
          <img :src="scope.row.pictureUrl" style="max-width: 100%; max-height: 100px;"
               @click="showDialog(scope.row.pictureUrl)">
        </template>
      </el-table-column>

      <el-table-column prop="content" label="文章内容">
        <template slot-scope="scope">
          <el-button @click="view(scope.row.content)" type="primary">查看内容</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="categoryName" label="分类名称">
      </el-table-column>
      <el-table-column prop="createUser" label="创建人">

      </el-table-column>
      <el-table-column prop="createTime" label="创建时间">
      </el-table-column>

      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="success" @click="handleEdit(scope.row)">编辑 <i class="el-icon-edit"></i></el-button>
          <el-popconfirm
              class="ml-5"
              confirm-button-text='确定'
              cancel-button-text='我再想想'
              icon="el-icon-info"
              icon-color="red"
              title="您确定删除吗？"
              @confirm="del(scope.row.id)"
          >
            <el-button type="danger" slot="reference">删除 <i class="el-icon-remove-outline"></i></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>

    </el-table>
    <div class="block" style="padding-top: 10px">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
    <!--    增加，修改表单-->
    <el-dialog title="文章" :visible.sync="dialogFormVisible" width="60%">
      <el-form label-width="80px" size="small" style="max-height: 60vh;overflow-y: auto;">
        <el-form-item label="标题">
          <el-input v-model="form.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="文章概览">
          <el-input v-model="form.overView" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="文章封面">
          <el-upload
              class="avatar-uploader"
              :action="'http://' + serverIp +':8082/file/upload'"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :headers="headers"
              :before-upload="beforeAvatarUpload"
          >
            <img v-if="pictureUrl" :src="pictureUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>


          </el-upload>
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="form.categoryId" placeholder="请选择">
            <el-option
                v-for="category in categoryList"
                :key="category.id"
                :label="category.categoryName"
                :value="category.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章内容">
          <mavon-editor ref="md" v-model="form.content" :ishljs="true" @imgAdd="$imgAdd"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="文章信息" :visible.sync="viewDialogVis" width="60%">
      <el-card style="max-height: 60vh;overflow-y: auto;">
        <div>
          <mavon-editor
              class="md"
              :value="content"
              :subfield="false"
              :defaultOpen="'preview'"
              :toolbarsFlag="false"
              :editable="false"
              :scrollStyle="true"
              :ishljs="true"
          />
        </div>
      </el-card>
    </el-dialog>

  </div>
</template>

<script>
import axios from '@/request/index.js'
import {serverIp} from "../../../public/config";

export default {
  name: "article",
  data() {

    return {
      imageUrl: "",
      dialogVisible: false,
      serverIp: serverIp,
      tableData: [],
      pageSize: 5,
      pageNum: 1,
      total: 0,
      title: "",
      token: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")).token : "",
      dialogFormVisible: false,
      form: {},
      multipleSelection: [],
      content: '',
      viewDialogVis: false,
      categoryList:[]

    }
  },
  computed: {
    headers() {
      return {
        token: `${this.token}`,
      };
    },
    pictureUrl() {
      return this.form.pictureUrl
    },

  },
  methods: {

    showDialog(url) {
      this.dialogVisible = true
      this.imageUrl = url
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    handleAvatarSuccess(res) {
      // console.log(res)
      this.form.pictureUrl = res.data
      this.pictureUrl = res.data
      console.log(this.form.pictureUrl)
    },
    view(content) {
      this.content = content
      this.viewDialogVis = true
    },
    /**
     * 刷新列表
     */
    load() {
      axios.post('article/getArticlesByPage', {
        pageSize: this.pageSize,
        pageNum: this.pageNum,
        title: this.title,


      }).then((res) => {
        console.log(res)
        this.tableData = res.data.records;
        this.total = res.data.total;
      })
    },
    /**
     * 刷新列表
     */
    getCategory() {
      axios.post('category/getAllCategory').then((res) => {
        console.log(res)
        this.categoryList = res.data;
        console.log("我在这")
        console.log(this.categoryList)
      })
    },
    handleSelectionChange(val) {
      console.log(val)
      this.multipleSelection = val
    },
    $imgAdd(pos, $file) {
      let $vm = this.$refs.md
      // 第一步.将图片上传到服务器.
      const formData = new FormData();
      formData.append('file', $file);
      axios.post("/file/upload", formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then((res) => {
        // 第二步.将返回的url替换到文本原位置![...](./0) -> ![...](url)
        $vm.$img2Url(pos, res.data);
      })
    },
    delBatch() {
      let ids = this.multipleSelection.map(v => v.id)  // [{}, {}, {}] => [1,2,3]
      axios.post("/article/del/batch", ids).then(res => {
        if (res.code === 200) {
          this.$message.success("批量删除成功")
          this.load()
        } else {
          this.$message.error("批量删除失败")
        }
      })
    },
    /**
     * 每页数据数量改变事件
     * @param val
     */
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.load();
    },
    /**
     * 页数改变事件
     * @param val
     */
    handleCurrentChange(val) {
      this.pageNum = val;
      this.load();
      console.log(`当前页: ${val}`);
    },
    reset() {
      this.title = "";

      this.load();
    },
    handleAdd() {
      this.dialogFormVisible = true
      this.form = {}
    },
    save() {
      axios.post("/article/saveArticle", this.form).then(res => {
        console.log(res)
        if (res.code === 200) {
          this.$message.success("保存成功")
          this.dialogFormVisible = false
          this.load()
        } else {
          this.$message.error("保存失败")
        }
      })
    },
    handleEdit(row) {
      this.form = row
      this.dialogFormVisible = true
    },
    del(id) {
      axios.post("/article/deleteById", {
        id: id
      }).then(res => {
        if (res.code === 200) {
          this.$message.success("删除成功")
          this.load()
        } else {
          this.$message.error("删除失败")
        }
      })
    },
  },
  created() {
    this.load();
    this.getCategory();
  },

}
</script>

<style scoped>
.avatar-uploader {
  padding-bottom: 10px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 138px;
  height: 138px;
  line-height: 138px;
  text-align: center;
}

.avatar {
  width: 138px;
  height: 138px;
  display: block;
}
</style>
